package com.lagou.test

import scala.collection.immutable.List;

class UserInfo(uid:String, pid:String, hour:Int, minutes:Int){
  var _uid: String = uid;
  var _pid: String = pid;
  var _hour: Int = hour;
  var _minutes: Int = minutes;

  def mergeMiniutes(min: Int): Unit = {
    _minutes = _minutes + min
  }
}

object UserInfoMerge {
  def main(args: Array[String]): Unit = {
//    UserA,LocationA,8,60
//    UserA,LocationA,9,60
//    UserB,LocationB,10,60
//    UserB,LocationB,11,80
    var log0 = new UserInfo("UserA","LocationA",8,60);
    var log1 = new UserInfo("UserA","LocationA",11,60);//测试间断情况
    var log2 = new UserInfo("UserB","LocationB",10,60);
    var log3 = new UserInfo("UserA","LocationA",9,60);
    var log4 = new UserInfo("UserB","LocationB",11,60);
    var log5 = new UserInfo("UserB","LocationC",12,80);//测试换地址

    val logs = List(log0,log1,log2,log3,log4,log5);
//    println(logs(0)._uid)
    val map: Map[String, List[UserInfo]] = logs.groupBy(_._uid)
//    println(map)
//    println(map.keys)
//    println(map.values)
//    println(map("UserA").toBuffer)
    //结果
    var merged: Seq[UserInfo] = Seq();

    for (lst <- map){
      //保证按启动时间顺序排列
      val sorted = lst._2.sortWith(_._hour < _._hour)
      println(s"处理 ${lst._1} 的 ${sorted.length} 条数据")
      for(i <- 0 until(sorted.length)) {
        //把连续的数据转移到后面的数据上
        if (i > 0 && sorted(i)._pid == sorted(i-1)._pid && sorted(i-1)._hour + sorted(i-1)._minutes / 60 == sorted(i)._hour){
//          sorted(i)._minutes = sorted(i-1)._minutes + sorted(i)._minutes
          sorted(i)._hour = sorted(i-1)._hour;
          sorted(i).mergeMiniutes(sorted(i-1)._minutes)
          println(s"合并 idx = ${i-1} Hour = ${sorted(i)._hour}  ; Minute = ${sorted(i)._minutes}")
        }
        //如果是最后一条，或者是不连续就组到新队列中
        if(i == sorted.length - 1
          || i < sorted.length - 1 && sorted(i)._hour + sorted(i)._minutes / 60 != sorted(i+1)._hour
          || sorted(i)._pid != sorted(i+1)._pid){
          merged :+= sorted(i)
          println(s"入表 idx = ${i} Hour = ${sorted(i)._hour}  ; Minute = ${sorted(i)._minutes}")
        }
      }
    }

    println(s"结果总数 = ${merged.length}")
    println(s"=========================")
    for(tmp <- merged){
      println(s"合并结果 UID = ${tmp._uid}  ; PID = ${tmp._pid}  ; Hour = ${tmp._hour}  ; Minute = ${tmp._minutes}")
    }
  }
}
